//
//  SuperSDKConnector.m
//  Unity-iPhone
//
//  Created by wyht－ios－dev on 15/10/23.
//
//

#import <UIKit/UIKit.h>
#import "UnityInterface.h"
#import "SuperSDKConnector.h"
#import "YCSuperSDK//libSuperSDK.h"
#import "YCSuperSDK/SSDKDataKeys.h"
#import "YCSuperSDK/SSDKEventKeys.h"
#import "YCSuperSDK/SSDKEventManager.h"

static NSString *callBackUserObjectN;
static NSString *callBackPayObjectN;
static NSString *callBackUserFunN;
static NSString *callBackPayFunN;


#if defined(_cplusplus)
extern "C"{
#endif
    
    NSString *CreateNSString (const char * string)
    {
        if(string)
            return [NSString stringWithUTF8String: string];
        else
            return [NSString stringWithUTF8String: ""];
    }
    
    //废弃适配unityFramework1.1.9
    void iosInit(char* appid,char* appSecret,char* privateKey,char* callBackUserObject,
                 char* callBackUserFun,char* callBackPayObject,char* callBackPayFun,bool debugMode)
    {
        callBackPayObjectN=CreateNSString(callBackPayObject);
        callBackPayFunN=CreateNSString(callBackPayFun);
        callBackUserFunN=CreateNSString(callBackUserFun);
        callBackUserObjectN=CreateNSString(callBackUserObject);
        
        [SuperSDK initWithAppId:CreateNSString(appid)
                      appSecret:CreateNSString(appSecret)
                     privateKey:CreateNSString(privateKey)
                    userDelegate:(id<SSDKDelegate>)[[SuperSDKConnector alloc] init]
                    payDelegate:(id<SSDKDelegate>)[[SuperSDKConnector alloc] init]
                      debugMode:debugMode];
        
    }
    
    //启用,从unityFramework1.1.10开始
    void iosInitWithJson(char* jsonStr)
    {
        NSString *jsonData=CreateNSString(jsonStr);
        NSError *readError = nil;
        NSData *dataNS = [jsonData dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *obj = [NSJSONSerialization JSONObjectWithData:dataNS
                                                            options:NSJSONReadingMutableLeaves
                                                              error:&readError];
        NSString *appId=[[obj objectForKey:@"paramData"] objectForKey:@"appId"];
        NSString *appSecret=[[obj objectForKey:@"paramData"] objectForKey:@"appSecret"];
        NSString *privateKey=[[obj objectForKey:@"paramData"] objectForKey:@"privateKey"];
        callBackPayObjectN=[[obj objectForKey:@"paramData"] objectForKey:@"game_object_for_paycallback"];
        callBackPayFunN=[[obj objectForKey:@"paramData"] objectForKey:@"paycallback"];
        callBackUserFunN=[[obj objectForKey:@"paramData"] objectForKey:@"usercallback"];
        callBackUserObjectN=[[obj objectForKey:@"paramData"] objectForKey:@"game_object_for_usercallback"];
        [SuperSDK initWithAppId:appId
                      appSecret:appSecret
                     privateKey:privateKey
                   userDelegate:(id<SSDKDelegate>)[[SuperSDKConnector alloc] init]
                    payDelegate:(id<SSDKDelegate>)[[SuperSDKConnector alloc] init]
                      debugMode:true];
    }
    
    void iosLogin(char* data)
    {
        NSString *LoginData=CreateNSString(data);
        NSError *readError = nil;
        NSData *dataNS = [LoginData dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *obj = [NSJSONSerialization JSONObjectWithData:dataNS
                                                    options:NSJSONReadingMutableLeaves
                                                  error:&readError];

        NSString *loginUrl=[[obj objectForKey:@"paramData"] objectForKey:@"loginReqUrl"];
        NSString *serverID=[[obj objectForKey:@"paramData"] objectForKey:@"serverID"];
        NSString *extraData=[[obj objectForKey:@"paramData"] objectForKey:@"data"];
        
        //如果配置了debug登录验证地址，则使用debug地址，而不是用unity传过来的登录验证地址
        NSDictionary *config = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"SSDKConfig"];
        NSString *debugLoginUrl = [config objectForKey:@"DEBUG_LOGIN_URL"];
        if (debugLoginUrl != nil && debugLoginUrl.length > 0) {
            loginUrl = debugLoginUrl;
        }
        
        if([serverID length]==0)
            [SuperSDK login:loginUrl appData:extraData];
        else
            [SuperSDK login:[serverID integerValue] loginReqUrl:loginUrl appData:extraData];
    }
    
    void iosRelease()
    {
        [SuperSDK destory];
    }
    
    //废弃适配unityFramework1.1.9
    void iosPay(char* uid,char* productId,int productCount,char* productName,char* gameUid,
                int serverId,char* orderAmount,char* roleId,char* roleName,int roleGrade,
                char* roleBalance,char* appData)
    {
        SSDKPayInfo *payInfo = [[SSDKPayInfo alloc] init];
        
        payInfo.gameUid = CreateNSString(gameUid);
        payInfo.orderAmount = CreateNSString(orderAmount);
        payInfo.productCount = productCount;
        payInfo.productId =CreateNSString(productId);
        payInfo.productName = CreateNSString(productName);
        payInfo.serverId = serverId;
        
        payInfo.roleId = CreateNSString(roleId);
        payInfo.roleName = CreateNSString(roleName);
        payInfo.roleGrade = roleGrade;
        payInfo.roleBalance =CreateNSString(roleBalance);
        
        payInfo.appData = CreateNSString(appData);
        
        payInfo.uid = CreateNSString(uid);
        
        [SuperSDK payWithPayInfo:payInfo];
    }
    
    //启用,从unityFramework1.1.10开始
    void iosPayWithJson(char* jsonStr)
    {
        NSString *jsonData=CreateNSString(jsonStr);
        NSError *readError = nil;
        NSData *dataNS = [jsonData dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *obj = [NSJSONSerialization JSONObjectWithData:dataNS
                                                            options:NSJSONReadingMutableLeaves
                                                              error:&readError];
        NSString *superSdkUid=[[obj objectForKey:@"paramData"] objectForKey:@"supersdk_uid"];
        NSString *gameUid=[[obj objectForKey:@"paramData"] objectForKey:@"game_uid"];
        NSString *orderAmount=[[obj objectForKey:@"paramData"] objectForKey:@"order_amount"];
        NSString *productCount=[[obj objectForKey:@"paramData"] objectForKey:@"product_count"];
        NSString *productId=[[obj objectForKey:@"paramData"] objectForKey:@"product_id"];
        NSString *productName=[[obj objectForKey:@"paramData"] objectForKey:@"product_name"];
        NSString *serverId=[[obj objectForKey:@"paramData"] objectForKey:@"server_id"];
        NSString *roleId=[[obj objectForKey:@"paramData"] objectForKey:@"role_id"];
        NSString *roleName=[[obj objectForKey:@"paramData"] objectForKey:@"role_name"];
        NSString *roleGrade=[[obj objectForKey:@"paramData"] objectForKey:@"role_grade"];
        NSString *roleBalance=[[obj objectForKey:@"paramData"] objectForKey:@"role_balance"];
        NSString *appData=[[obj objectForKey:@"paramData"] objectForKey:@"app_data"];
        NSString *cpOrderId=[[obj objectForKey:@"paramData"] objectForKey:@"cp_order_id"];
        NSString *noticeUrl=[[obj objectForKey:@"paramData"] objectForKey:@"notice_url"];
        SSDKPayInfo *payInfo = [[SSDKPayInfo alloc] init];
        payInfo.gameUid = gameUid;
        payInfo.orderAmount = orderAmount;
        payInfo.productCount = [productCount intValue];
        payInfo.productId = productId;
        payInfo.productName = productName;
        payInfo.serverId = [serverId intValue];
        payInfo.roleId = roleId;
        payInfo.roleName = roleName;
        payInfo.roleGrade = [roleGrade intValue];
        payInfo.roleBalance = roleBalance;
        payInfo.appData = appData;
        payInfo.uid = superSdkUid;
        if(cpOrderId!=nil && cpOrderId.length>0)
            payInfo.cpOrderId=cpOrderId;
        if(noticeUrl!=nil && noticeUrl.length>0)
            payInfo.noticeUrl=noticeUrl;
        
        [SuperSDK payWithPayInfo:payInfo];
        
    }
    
    void iosCall(char* funInfo)
    {
        NSString *funInfoN=CreateNSString(funInfo);
        NSData *jsonData = [funInfoN dataUsingEncoding:NSUTF8StringEncoding];
        NSError *err;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                            options:NSJSONReadingMutableContainers
                                                              error:&err];
        if(err) {
            NSLog(@"call Error：json解析失败：%@",err);
            return;
        }
        
        NSString *funName=[dic objectForKey:@"funName"];
        NSDictionary *paramData=[dic objectForKey:@"paramData"];
        
        if([funName isEqualToString:@"logout"])
        {
            [SuperSDK call:@"logout" with:nil];
        }
        
        if([funName isEqualToString:@"enterPlatform"])
        {
            [SuperSDK call:@"enterPlatform" with:nil];
        }
        
        if([funName isEqualToString:@"hideFloatButton"])
        {
            [SuperSDK call:@"hideFloatButton" with:nil];
        }
        
        if([funName isEqualToString:@"switchAccount"])
        {
            [SuperSDK call:@"switchAccount" with:nil];
        }else
        if([funName isEqualToString:@"exit"])
        {
            [SuperSDK call:@"exit" with:nil];
        }else
        if([funName isEqualToString:@"destroy"])
        {
            [SuperSDK destory];
        }else
        if([funName isEqualToString:@"realNameRegister"])
        {
            [SuperSDK call:@"realNameRegister" with:nil];
        }else
        if([funName isEqualToString:@"antiAddictionQuery"])
        {
            [SuperSDK call:@"antiAddictionQuery" with:nil];
        }else
        if([funName isEqualToString:@"otherLogin"])
        {
           [SuperSDK call:@"otherLogin" with:paramData];
            
        }else
        if([funName isEqualToString:@"showFloatButton"])
        {
            [SuperSDK call:@"showFloatButton" with:[paramData objectForKey:@"position"]];
        }else
        if([funName isEqualToString:@"submitData"])
        {
            [SuperSDK call:@"submitData" with:paramData];
        }

    }
    
    const char * iosIsSupport(char* funName)
    {
        char* res=NULL;
        char* flag="true";
        
        if([SuperSDK isSupported: CreateNSString(funName)])
        {
            flag="true";
        }
        else
        {
            flag="false";
        }
        
        res = (char*)malloc(strlen(flag) + 1);
        strcpy(res, flag);
        
        return res;
    }
    
    const char * iosIsLogin()
    {
        char* res=NULL;
        char* flag="false";
        
        if([SuperSDK isLogin])
        {
            flag="true";
        }
        else
        {
            flag="false";
        }
        
        res = (char*)malloc(strlen(flag) + 1);
        strcpy(res, flag);
        
        return res;
    }
    
    //发布版本号
    const char * iosGetVersionName()
    {
        char* res=NULL;
        
        NSString *phoneVersion=[SuperSDK getVersionName];
        
        res = (char*)malloc(strlen([phoneVersion UTF8String]) + 1);
        strcpy(res, [phoneVersion UTF8String]);
        
        return res;
    }
    
    //内部版本号
    const char * iosGetVersionCode() {
        
        char* res=NULL;
        NSString *phoneVersion=[SuperSDK getVersionCode];
        res = (char*)malloc(strlen([phoneVersion UTF8String]) + 1);
        strcpy(res, [phoneVersion UTF8String]);
        
        return res;
    }
    
    //Plist中自定义的数据
    const char * iosGetUserDefinedValue(char* key)
    {
        NSString *myValue=@"";
        char* res=NULL;
        
        if(key!=NULL)
        {
            myValue=[SuperSDK getUserDefinedValue:CreateNSString(key)];
        }
        
        if(myValue!=nil)
        {
            res = (char*)malloc(strlen([myValue UTF8String]) + 1);
        }
        else
        {
            myValue=@"";
            res = (char*)malloc(strlen("") + 1);
        }
        
        strcpy(res, [myValue UTF8String]);
        
        return res;
    }
    
#if defined(_cplusplus)
    }
#endif

@interface SuperSDKConnector () <SSDKDelegate>

@end

@implementation SuperSDKConnector

- (void) callbackWithCode:(int)code jsonData:(NSString *)json {
    
    NSString *msg=json;
    NSString *msgCode=[NSString stringWithFormat:@"%d",code];
    NSMutableDictionary *dic=[[NSMutableDictionary alloc] init];
    [dic setObject:msgCode forKey:@"action"];
    [dic setObject:msg forKey:@"resData"];
    
    NSError *error;
    NSData *jsonData=[NSJSONSerialization dataWithJSONObject:dic options:0 error:&error];
    NSString *targetMsg=[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    if(code==2001||code==2002||code==2003||code==2004||code==2005||code==2006||code==2007||code==2008) {
        UnitySendMessage([callBackPayObjectN UTF8String], [callBackPayFunN UTF8String], [targetMsg UTF8String]);
    } else {
        UnitySendMessage([callBackUserObjectN UTF8String], [callBackUserFunN UTF8String], [targetMsg UTF8String]);
    }
    
}

- (void) initInfo {
    [SSDKEventManager addObsver:self selector:@selector(pluinCallback:) name:EVENT_PLUGIN_CALLBACK object:nil className:@"SuperSDKConnector"];
}

//回调Unity端
- (void) pluinCallback:(NSNotification*) notification {
    NSString *obj = [[notification object] objectForKey:CALLBACK_E_OBJ];
    NSString *method = [[notification object] objectForKey:CALLBACK_E_METHOD];
    NSString *msg = [[notification object] objectForKey:CALLBACK_E_MSG];
    if (obj!=nil && method!=nil) {
        UnitySendMessage([obj UTF8String], [method UTF8String], [msg UTF8String]);
    }
}

@end



